using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesAdminAuthorizedDetail : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;

    #region EntityID
    protected string EntityID
    {
        get
        {
            return ViewState["EntityID"].ToString();
        }

        set
        {
            ViewState["EntityID"] = value;
        }
    }
    #endregion

    #region AuthorizerID
    protected string AuthorizerID
    {
        get
        {
            return ViewState["AuthorizerID"].ToString();
        }

        set
        {
            ViewState["AuthorizerID"] = value;
        }
    }
    #endregion

    #region ErrorMessage
    protected string ErrorMessage
    {
        get
        {
            return ViewState["ErrorMessage"].ToString();
        }

        set
        {
            ViewState["ErrorMessage"] = value;
        }
    }
    #endregion

    #region MinMaxMessage
    protected string MinMaxMessage
    {
        get
        {
            return ViewState["MinMaxMessage"].ToString();
        }

        set
        {
            ViewState["MinMaxMessage"] = value;
        }
    }
    #endregion

    #region MinMaxMessage2
    protected string MinMaxMessage2
    {
        get
        {
            return ViewState["MinMaxMessage2"].ToString();
        }

        set
        {
            ViewState["MinMaxMessage2"] = value;
        }
    }
    #endregion

    #region LevelMessage
    protected string LevelMessage
    {
        get
        {
            return ViewState["LevelMessage"].ToString();
        }

        set
        {
            ViewState["LevelMessage"] = value;
        }
    }
    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        // always hide
        this.Table_MessageBox.Visible = false;

        if (!IsPostBack)
        {
            this.SwitchLanguage();
            this.PageComponentSetup();
            this.SwitchLanguage();

            this.LoadData();

            // log down the history
            this.CurLogManager.LogMessage("[GonzalesAdminAuthorizedDetail] : Authorizer detail (" + this.AuthorizerID + ", " + this.LabelValue_Personnel.Text + ") viewed", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }
    }
    #endregion

    #region Button_Submit_Click
    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        if (this.DataValidate())
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                if (CurUserManager.UpdateAuthorizer(
                    this.EntityID,
                    this.AuthorizerID,
                    Convert.ToInt32(this.TextBox_Level.Text),
                    (new Currency(this.DropDownList_Currency.SelectedValue, this.DropDownList_Currency.SelectedItem.Text)),
                    Convert.ToDecimal(this.TextBox_Min.Text),
                    Convert.ToDecimal(this.TextBox_Max.Text)))
                {
                    // log down the history
                    //this.CurLogManager.LogMessage("[GonzalesAdminAuthorizedDetail] : Authorizer detail (" + this.AuthorizerID + ", " + this.LabelValue_Personnel.Text + ") edited", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                    //FRANK
                    this.CurLogManager.LogMessageFull("[GonzalesAdminAuthorizedDetail] : Authorizer detail (" + this.AuthorizerID + ", " + this.LabelValue_Personnel.Text + ") edited", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User
                        , this.AuthorizerID,
                        "", "Authorizer", "Update", "", "", "", "", "", "", "", "", "", "", "", Convert.ToDouble(this.TextBox_Min.Text), Convert.ToDouble(this.TextBox_Max.Text), "GonzalesAdminAuthorizedListing","0");

                    // Added by thangnv 20130619 -- change log
                    Authoriser CurAuthorizer = CurUserManager.GetAuthorizerUserByID(this.AuthorizerID, this.EntityID);
                    
                    if (CurAuthorizer != null)
                    {
                        #region Logged By Role
                        string LoggedByRole = string.Empty;
                        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
                        {
                            if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinancialManager)
                            {
                                LoggedByRole = GonzalesUserRole.FinanceManager;
                            }
                            else
                            {
                                LoggedByRole = GonzalesUserRole.FinanceAdmin;
                            }
                        }
                        else if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin)
                        {
                            LoggedByRole = GonzalesUserRole.PowerAdmin;
                        }
                        else if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsITAdmin)
                        {
                            LoggedByRole = GonzalesUserRole.ITAdmin;
                        }
                        #endregion
                        this.CurLogManager.ChangeLogAuthorizer(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, 
                            this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, 
                            CurAuthorizer.EmployeeID, 
                            CurAuthorizer.DisplayName,
                            CurAuthorizer.FromCompany.InternalID,
                            CurAuthorizer.FromCompany.CompanyCode,
                            CurAuthorizer.FromCompany.CompanyName, 
                            GonzalesUserAction.Modified, 
                            CurAuthorizer.FromCompany.Entity.InternalID, 
                            this.AuthorizerID,
                            Int32.Parse(this.TextBox_Level.Text), 
                            this.DropDownList_Currency.SelectedValue, 
                            decimal.Parse(this.TextBox_Min.Text), 
                            decimal.Parse(this.TextBox_Max.Text), LoggedByRole, CurAuthorizer.EmailID,
                            this.EntityID);
                    }

                    Response.Redirect("GonzalesAdminAuthorizedListing.aspx?entity=" + this.EntityID);
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesAdminAuthorizedDetail.Button_Submit_Click] : Failure in CurUserManager.UpdateAuthorizer() : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.ErrorMessage + LogID);
                }
            }
        }
    }
    #endregion

    #region ImageButton_Cancel_Click
    protected void ImageButton_Cancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("GonzalesAdminAuthorizedListing.aspx?entity=" + this.EntityID);
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        // setup currency
        using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
        {
            MasterBaseCollection ResultList = CurCurrencyManager.GetAllCurrency();
            if (ResultList != null)
            {
                for (int x = 0; x < ResultList.Count; x++)
                {
                    this.DropDownList_Currency.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                }
            }
            else
            {
                // display error

                this.CurLogManager.LogError("[GonzalesAdminAuthorizedDetail.PageComponentSetup] : Failed on CurCurrencyManager.GetAllEntity() : " + CurCurrencyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

            }
        }

        this.Button_Browse.Attributes["onclick"] = "ShowModal('AddressBook', document.getElementById('ModalResult')); return false;";
        this.ImageButton_Cancel.Attributes["onclick"] = "return confirm('All unsaved data will be lost, are you sure?');";
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_AuthorizedLimit2.Text = CurLanguageFactory.DisplayValue("AuthorizedLimit2");
                this.Label_AuthorizedLimit3.Text = CurLanguageFactory.DisplayValue("AuthorizedLimit3");
                this.Label_Entity.Text = CurLanguageFactory.DisplayValue("Entity");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Personnel.Text = CurLanguageFactory.DisplayValue("Personnel");
                this.Label_To2.Text = CurLanguageFactory.DisplayValue("To2");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesAdminAuthorizedDetail.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        if (Request.QueryString["entity"] != null &&
            Request.QueryString["uid"] != null && Request.QueryString["uid"].Length == 36)
        {
            this.EntityID = Request.QueryString["entity"];
            this.AuthorizerID = Request.QueryString["uid"];

            // setup detail
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                Authoriser CurAuthorizer = CurUserManager.GetAuthorizersByEntity(this.EntityID, this.AuthorizerID);

                this.LabelValue_Personnel.Text = CurAuthorizer.DisplayName;
                this.TextBox_Level.Text = CurAuthorizer.Level.ToString();
                this.TextBox_Min.Text = CurAuthorizer.MinLimit.ToString();
                this.TextBox_Max.Text = CurAuthorizer.MaxLimit.ToString();
                this.DropDownList_Currency.Items.FindByValue(CurAuthorizer.LimitCurrency.InternalID).Selected = true;
            }

            // setup entity
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                Entity CurEntity = CurEntityManager.GetEntityDetailByCode(this.EntityID);
                this.LabelValue_Entity.Text = CurEntity.DisplayName;
            }
        }
        else
        {
            // log
        }
    }

    #endregion

    #region DataValidate
    protected bool DataValidate()
    {
        bool smooth = true;
        StringBuilder ErrorMessageBuilder = new StringBuilder("<ul>");

        // validate min and max
        decimal MinAmount = 0, MaxAmount = 0;
        if (this.TextBox_Min.Text.Trim().Length == 0 || !decimal.TryParse(this.TextBox_Min.Text, out MinAmount) ||
            this.TextBox_Max.Text.Trim().Length == 0 || !decimal.TryParse(this.TextBox_Max.Text, out MaxAmount) ||
            MinAmount < 0 || MaxAmount < 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.MinMaxMessage + "</li>");
            smooth = false;
        }
        else
        {
            if (MinAmount > MaxAmount || MinAmount == MaxAmount)
            {
                ErrorMessageBuilder.AppendLine("<li>" + this.MinMaxMessage2 + "</li>");
                smooth = false;
            }
        }

        // validate level
        int InputLevel = 0;
        if (this.TextBox_Level.Text.Trim().Length == 0 || !Int32.TryParse(this.TextBox_Level.Text, out InputLevel) || InputLevel < 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.LevelMessage + "</li>");
            smooth = false;
        }

        ErrorMessageBuilder.AppendLine("</ul>");

        if (!smooth)
        {
            this.ShowErrorMessage(ErrorMessageBuilder.ToString());
        }
        

        return smooth;
    }
    #endregion

    #endregion

}
